/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.getElementsByClassName('bottem2')].slice(-1)
  let url = lastNrPage.querySelector('a:nth-child(4)').href

  const response = await fetch(url)
  const decoder = new TextDecoder('utf8')
  const html = decoder.decode(await response.arrayBuffer())
  let div = document.createElement('div')
  div.innerHTML = html

  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  for (let pageClassName of ['.bottem1', '.bottem2']) {
    let pageDom = div.querySelector(pageClassName)
    if (pageDom.querySelectorAll('a').length >= 5) {
      pageDom.insertBefore(alink.cloneNode(true), pageDom.children[4])
      console.log('插入本页链接')
      console.log(pageDom)
      pageDom.removeChild(pageDom.children[5])
      console.log('插入本页链接后的删除操作')
      console.log(pageDom)
    } else {
      pageDom.appendChild(alink.cloneNode(true))
    }
  }

  div.querySelector('.box_con').style.borderLeftWidth = '0'
  div.querySelector('.box_con').style.borderRrightWidth = '0'
  div.querySelector('.box_con').style.borderBottomWidth = '0'

  cleanPage(div)

  let [lastContent] = [...document.getElementsByClassName('box_con')].slice(-1)
  lastContent.appendChild(div)
  return { div, url }
}

/**包装cleanPage方法 */
function cleanPage(context = document) {
  $chromePlugin.cleanPage(context, ['.contnew', '.apprecom', '.ywtop', '.header', '.con_top', '.lm', '#conter_tip', '.footer'])
    
  let { host, href } = location
  if (host == 'www.biqusa.com') {
    // 清理一些特殊情况下的节点
    context.querySelector('#content')?.previousElementSibling?.remove()
    context.querySelector('#content p')?.remove()
    context.querySelector('#content div[align="center"]')?.remove()
    // 在详情页移除导航栏
    href.endsWith('.html') && context.querySelector('.nav').remove()
    return
  }

  if (host == 'www.aixiashu.info') {
    // 在详情页移除导航栏
    href.endsWith('.html') && context.querySelector('.nav').remove()
    return
  }

}

$chromePlugin.loadQueueFn.push(cleanPage)

/**从页面获取书名 */
function getBookName() {
  const descriptionMeta = document.querySelector('meta[name="description"]');
  if (descriptionMeta) {
    const content = descriptionMeta.getAttribute('content');
    let matchResult = content.match(/《(.*)》/)
    if (matchResult && matchResult[1]) {
      return matchResult[1].trim();
    }
  }
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  let titleSelector = dom.querySelector('.bookname h1') ? '.bookname h1' : '.bookname'
  _addObserver('.box_con', titleSelector, dom, url)
}
